from unittest import result
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from website_server.utils import getID, getTime, http_post, log_in, model_to_list
from website_server.models import RoomTab, RoomUserTab, UserinfoTab

# 创建聊天室
@log_in
def createChatRoom(request):
  username = UserinfoTab.objects.filter(username=request.session.get('user')).first()
  if RoomTab.objects.filter(username=username).first():
    return HttpResponse('单个用户只能创建一个房间')
  elif username:
    rq = request.POST
    room = RoomTab()
    room.chatid = getID()
    room.username = username
    room.title = rq.get('title')
    room.channel = rq.get('channel')
    room.time = getTime()
    room.save()
    return JsonResponse({'data':model_to_dict(room)})
  else:
    return HttpResponse('创建失败')

# 获取房间信息
@log_in
def getRoomInfo(request):
  rq = request.POST
  room = RoomTab.objects.filter(chatid=rq.get('id')).first()
  if room:
    userList = RoomUserTab.objects.filter(chatid=rq.get('id'))
    userList = [{**model_to_dict(x.username)} for x in userList]
    result = {
      **model_to_dict(room),
      'picture': room.username.picture,
      'name': room.username.name,
      'userList': userList
    }
    return JsonResponse(result)
  else:
    return HttpResponse('房间不存在')

# 获取所有房间
@http_post
def getAllRoom(request):
  room = RoomTab.objects.all().order_by('-time')
  result = [{
    **model_to_dict(x),
    'count': RoomUserTab.objects.filter(chatid=x.chatid).count(),
    'name': x.username.name
    } for x in room]
  return JsonResponse({'data':result})

